<template>
  <div class="chart" ref="chart" style="height: 100%"></div>
</template>

<script>
import * as echarts from 'echarts'
import ecStat from 'echarts-stat'

export default {
  name: 'BarCharts',
  props: {
    filed: {
      type: String,
      default: ''
    },
    data: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      chart: null
    }
  },
  watch: {
    data () {
      this.draw()
    }
  },
  methods: {
    draw () {

      this.chart.clear()
      const seriesData = this.data.map((item) => {
        return [Number(item.field), Number(item.moranI)]
      })

      const option = {
        dataset: [
          {
            source: seriesData
          },
          {
            transform: {
              type: 'ecStat:regression'
              // 'linear' by default.
              // config: { method: 'linear', formulaOn: 'end'}
            }
          }
        ],
        grid: {
          left: 20,
          right: 20,
          bottom: 20,
          top: 50,
          containLabel: true
        },
        tooltip: {
          trigger: 'item'
        },
        xAxis: {
          type: 'value',
          scale: true,
          // name: this.filed,
          axisLabel: {
            formatter: '{value}'
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          },
          axisTick: {
            show: false
          },
          axisLine: {
            onZero: false
          }
        },
        yAxis: {
          type: 'value',
          name: 'Moran I',
          scale: true,
          position: 'left',
          axisLine: {
            onZero: false
          },
          axisLabel: {
            formatter: '{value}'
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: '',
            type: 'scatter'
          },
          {
            name: 'line',
            type: 'line',
            datasetIndex: 1,
            symbolSize: 0.1,
            symbol: 'circle',
            label: { show: false, fontSize: 16 },
            labelLayout: { dx: -20 },
            encode: { label: 2, tooltip: 1 }
          }
        ]
      }
      this.chart.setOption(option)
    }
  },
  mounted () {
    this.chart = echarts.init(this.$refs.chart)
    echarts.registerTransform(ecStat.transform.regression)
    this.draw()
  },
  beforeDestroy () {
    echarts.dispose(this.chart)
    this.chart = null
  }
}
</script>

<style>
.chart {
  width: 100%;
  height: 100%;
}
</style>
